package com.huluobo.h3kotlindemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.h3kotlindemo.MainActivity
import com.huluobo.h3kotlindemo.R
import com.huluobo.h3kotlindemo.base.BaseMVVMActivity
import com.huluobo.h3kotlindemo.databinding.ActivityLoginBinding
import com.huluobo.h3kotlindemo.db.DatabaseUtil
import com.huluobo.h3kotlindemo.net.Const

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding>() {
    lateinit var viewModel: LoginViewModel
    override fun initData() {
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]

        viewModel.loginSuccess.observe(this) {
            if (it.code == 200) {
                //保存token到sp
                SPUtils.getInstance().put(Const.SP_TOKEN, it.data.token)
                //保存用户到数据库
                DatabaseUtil.getDatabase().userInfoDao().insertUserINfo(it.data)
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.loginFailed.observe(this) {
            Log.i("TagA", "e:$it")
        }
    }

    override fun initView() {
        dataBinding.loginBtn.setOnClickListener {
            viewModel.login(dataBinding.loginUsername.text.toString(), dataBinding.loginPassword.text.toString())
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_login
}